﻿<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <title>百度地图</title>
    <style type="text/css">
        body, html, #allmap {
            width: 100%;
            height: 500px;
            overflow: hidden;
            margin: 0;
            font-family: "微软雅黑";
        }
    </style>
    <script type="text/javascript" src="/JS/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=8rOzoQfDj0tSvs3zDaDGOhMM"></script>
</head>
<body>
    <div id="s">上车地点<input type="text" id="sc" size="80" style="width:200px;" value="福州拓博听力康复中心" /></div>
    <div id="x">下车地点<input type="text" id="xc" size="80" style="width:200px;" value="福建省血液中心献血屋" /><input type="button" id="js" value="计算" onclick="javascript:js();" /></div>
    <div id="Div1">下车地点<input type="text" id="n" size="80" style="width:200px;" value="机场" /><input type="button" id="Button1" value="得到机场火车站" onclick="javascript: GetFJHC();" /></div>
    <div id="Div2"><input type="button" id="Button2" value="地址解析" onclick="javascript:dizhi();" /></div>
    <div id="Div3"><input type="button" id="Button3" value="更爱图片" onclick="javascript:img();" /></div>
    <div id="r-result">请输入:<input type="text" id="suggestId" size="80" style="width:500px;" /></div>
    <div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
    <div id="allmap" style="width:700px; height:400px;"></div>
    <div id="fjmsg" style="width:500px;height:300px;"></div>
</body>
</html>

<script type="text/javascript">
    var city = "福州市";
    var lng = 119.31133;
    var lat = 26.076212;
    var map = new BMap.Map("allmap", { enableMapClick: false });    // 创建Map实例
    map.enableScrollWheelZoom();
    map.enableDoubleClickZoom();
    map.enableDragging();
    map.enableContinuousZoom();
    map.enableInertialDragging();
    // 添加定位控件
    var geolocationControl = new BMap.GeolocationControl();
    geolocationControl.addEventListener("locationSuccess", function (e) {
        // 定位成功事件
        var address = '';
        address += e.addressComponent.province;
        address += e.addressComponent.city;
        address += e.addressComponent.district;
        address += e.addressComponent.street;
        address += e.addressComponent.streetNumber;
    });
    geolocationControl.addEventListener("locationError", function (e) {
        // 定位失败事件
        alert(e.message);
    });
    map.addControl(geolocationControl);

    //设置地图属性
    function add_custom_control(config, clickcallback) {
        var mp = config.mp;
        function ZoomControl() {
            // 默认停靠位置和偏移量
            this._position = config.position || '';
            this._html = config.html || '';
            this._id = config.id || '';
            this._class = config.classname || '';
            this._top = config.top || 0;
            this._width = config.width || 'auto';
            this._height = config.height || 'auto';
            this._style = config.style || {};

        }

        // 通过JavaScript的prototype属性继承于BMap.Control
        ZoomControl.prototype = new BMap.Control();

        // 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回
        // 在本方法中创建个div元素作为控件的容器,并将其添加到地图容器中
        ZoomControl.prototype.initialize = function (map) {
            var div = document.createElement("div");
            div.style.MozUserSelect = "none";
            div.style.WebkitUserSelect = "none";
            div.id = this._id,
            div.className = this._class,
            div.innerHTML = this._html;
            div.style.width = this._width;
            div.style.height = this._height;
            div.style.position = 'absolute';
            for (var key in this._style) {
                div.style[key] = this._style[key];
            }
            this._div = div;
            var _this = this;
            div.addEventListener('click', function (e) {
                e.stopPropagation();
                clickcallback && clickcallback(_this._div);
            });
            // 添加DOM元素到地图中
            map.getContainer().appendChild(div);
            var div_w = div.offsetWidth;
            var div_h = div.offsetHeight;
            var ssize = map.getSize();

            if (this._position == '') {
                this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
                this.defaultOffset = new BMap.Size((ssize.width - div_w) / 2, ssize.height / 2 - div_h);
            } else {
                switch (this._position[0]) {
                    case 'TOP_LEFT':
                        this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
                        break;
                    case 'TOP_RIGHT':
                        this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
                        break;
                    case 'BOTTOM_LEFT':
                        this.defaultAnchor = BMAP_ANCHOR_BOTTOM_LEFT;
                        break;
                    case 'BOTTOM_RIGHT':
                        this.defaultAnchor = BMAP_ANCHOR_BOTTOM_RIGHT;
                        break;
                }
                this.defaultOffset = new BMap.Size(this._position[1], this._position[2]);
            }
            // 将DOM元素返回
            return div;
        }
        // 创建控件
        var myZoomCtrl = new ZoomControl(config);
        // 添加到地图当中
        mp.addControl(myZoomCtrl);
        var pos = map.getCenter();//返回当前位置的经纬度
        //todo 根据坐标，查询附近的地理位置
        loadNearPoi(pos, function () {
            //加载成功
        })
        return myZoomCtrl;
    };

    //获取当前城市名称
    var LocalCity = new BMap.LocalCity();
    LocalCity.get(function (c) {
        if (c.name !== null || c.name !== undefined || c.name !== "") {
            city = c.name;
        }
        //如果参数没有带经纬度信息过来.采用浏览器定位
        if (getQueryString("lng") !== null || getQueryString("lng") !== undefined || getQueryString("lng") !== "" || getQueryString("lat") !== null || getQueryString("lat") !== undefined || getQueryString("lat") !== "")
        {
            // 浏览器定位获取经纬度
            var geolocation = new BMap.Geolocation();
            geolocation.getCurrentPosition(function (r) {
                if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                    var mk = new BMap.Marker(r.point);
                    map.addOverlay(mk);
                    map.panTo(r.point);
                    lng = r.point.lng;
                    lat = r.point.lat;
                }
                else {
                    alert("获取你的定位信息失败,失败码:["+ this.getStatus()+"],将采取默认经纬度.");
                }
            }, { enableHighAccuracy: true })
        }
        //console.log("当前城市:" + city + ",经纬度:" + lng + "," + lat);
        //开始初始化地图
        var startPOS = new BMap.Point(lng, lat);
        map.centerAndZoom(startPOS, 16);  // 初始化地图,设置中心点坐标和地图级别
        map.setCurrentCity(city);          // 设置地图显示的城市 此项是必须设置的
        //返回附近的函数
        loadNearPoi = function (point, callback) {
            var gc = new BMap.Geocoder();
            gc.getLocation(point, function (rs) {
                var fujinlist = '{list:[';
                rs.surroundingPois.forEach(function (poi) {
                    fujinlist += '{city:"' + poi.city + '",name:"' + poi.title + '",address:"' + poi.address + '",lat:' + poi.point.lat + ',lng:' + poi.point.lng + '},';
                });
                fujinlist = fujinlist.substring(0, fujinlist.length - 1) + ']}';
                //console.log(fujinlist);
                //JSON解析
                if (fujinlist == "{list:]}")
                {
                    console.log("当前位置附近没有可上车的地点,请移动地图重新选择.");
                }
                else
                {
                    var obj = eval(fujinlist);
                    var num = 1;
                    $(obj).each(function (index) {
                        var list = obj[index];
                        switch (num)
                        {
                            case 1:
                                console.log("当前:" + list.address);
                                $("#fjmsg").html("当前:" + list.address + "</br>");
                                break;
                            case 2:
                                console.log("附近:" + list.address);
                                $("#fjmsg").html("附近:" + list.address + "</br>");
                                break;
                            default:
                                console.log("address:" + list.address + "name:" + list.name + "经纬度:" + list.lng + "," + list.lat);
                                $("#fjmsg").val("address:" + list.address + "name:" + list.name + "经纬度:" + list.lng + "," + list.lat + "</br>");
                                break;
                        }
                        num++;
                    });
                    callback && callback();
                }
            });
        };
        //移动地图监听事件
        var f = null, map_searching = false;
        map.addEventListener("dragstart", function (i, j, h, g) {
            clearTimeout(f)
        });
        map.addEventListener("dragend", function (i, j, h, g) {
            f = window.setTimeout(function () {
                map_searching = true;
                var pos = map.getCenter();//返回当前位置的经纬度
                //todo 根据坐标，查询附近的地理位置
                loadNearPoi(pos, function () {
                    //加载成功
                })

            }, 500);
        });
        //创建上下车图标
        var sx = "<img src=\"images/shang.png\"/>";
        if (getQueryString("sx") !== null || getQueryString("sx") !== undefined || getQueryString("sx") !== "")
        {
            sx = "<img id='bdimg' src=\"images/" + getQueryString("sx") + ".png\"/>";
        }
        var center_control = add_custom_control({
            mp: map,
            width: "22px",
            height: "30px",
            html: sx
        }, function () {
            alert("你当前的位置");
        });
    })

    //计算距离预算价格
    function js() {
        var output = "需要";
        var searchComplete = function (results) {
            if (transit.getStatus() != BMAP_STATUS_SUCCESS) {
                return;
            }
            var plan = results.getPlan(0);
            output += plan.getDuration(true) + "\n";                //获取时间
            output += "总路程为：";
            output += plan.getDistance(true) + "\n";             //获取距离
        }
        var transit = new BMap.DrivingRoute(map, {
            renderOptions: { map: map },
            onSearchComplete: searchComplete,
            onPolylinesSet: function () {
                setTimeout(function () { alert(output) }, "1000");
            }
        });
        var qd = new BMap.Point(119.310863, 26.075922);
        var zd = new BMap.Point(119.298331, 26.077731);
        transit.search(qd, zd);
    }

    //获取机场和火车站
    function GetFJHC()
    {
        var options = {
            onSearchComplete: function (results) {
                // 判断状态是否正确
                if (local.getStatus() == BMAP_STATUS_SUCCESS) {
                    for (var i = 0; i < results.getCurrentNumPois() ; i++) {
                        console.log(results.getPoi(i).title);
                    }
                }
            }
        };
        var local = new BMap.LocalSearch(map, options);
        local.search(document.getElementById("n").value);
    }

    function dizhi()
    {
        var scpoint;
        // 创建地址解析器实例
        var myGeo = new BMap.Geocoder();
        // 将地址解析结果显示在地图上,并调整地图视野
        myGeo.getPoint("上海虹桥机场1号航站楼", function (scpoint) {
            if (scpoint) {
                console.log(scpoint.lat);
                console.log(scpoint.lng);
            } else {
                alert("您选择地址没有解析到结果!");
            }
        });
    }
    //获取URL参数
    function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return r[2]; return null;
    }
    function img() {
        document.getElementById("bdimg").src = "images/xia.png";
    }
</script>

<!--文本框搜索-->
<script type="text/javascript">
    // 百度地图API功能
    function G(id) {
        return document.getElementById(id);
    }

    var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
		{
		    "input": "suggestId"
		, "location": map
		});

    ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
        var str = "";
        var _value = e.fromitem.value;
        var value = "";
        if (e.fromitem.index > -1) {
            value = _value.province + _value.city + _value.district + _value.street + _value.business;
        }
        str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

        value = "";
        if (e.toitem.index > -1) {
            _value = e.toitem.value;
            value = _value.province + _value.city + _value.district + _value.street + _value.business;
        }
        str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
        G("searchResultPanel").innerHTML = str;
    });

    var myValue;
    ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
        var _value = e.item.value;
        myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
        G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

        setPlace();
    });

    function setPlace() {
        map.clearOverlays();    //清除地图上所有覆盖物
        function myFun() {
            var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
            map.centerAndZoom(pp, 18);
            map.addOverlay(new BMap.Marker(pp));    //添加标注
        }
        var local = new BMap.LocalSearch(map, { //智能搜索
            onSearchComplete: myFun
        });
        local.search(myValue);
    }
</script>